export default defineNuxtPlugin((nuxtApp) => {
  let isRefreshing = false
  let refreshSubscribers = []
  const config = useRuntimeConfig()
  const localePath = useLocalePath()
  const requestURl = location.origin;
  const processQueue = (error) => {
    const newToken = error ? null : userStore.token?.accessToken
    refreshSubscribers.forEach(sub => sub(error, newToken))
    refreshSubscribers = []
  }

  const createFetchHandler = (requiresAuth) => async (path, options) => {
    const userStore = useUserStore()
    
    // 动态构建 headers
    const headers = {
      ...options.headers,
      Authorization: requiresAuth 
        ? `Bearer ${userStore.token?.accessToken || ''}`
        : undefined
    }

    try {
      const response = await $fetch(path, {
        ...options,
        baseURL: requestURl + config.public.apiBase,
        // baseURL:requestURl,
        headers,
        async onResponseError({ response }) {
          if (response.status === 401 && requiresAuth) {
            if (!isRefreshing) {
              isRefreshing = true
              try {
                const { _data } = await $fetch.raw(requestURl + config.public.apiBase + '/api/auth/jwt/refresh-token', {
                  method: 'POST',
                  body: { 
                    refreshToken: userStore.token?.refreshToken 
                  }
                })
                if(_data.status === -1){
                  userStore.clearUser()
                  nuxtApp.$router.push(
                    localePath('/Login') + `?redirect=${encodeURIComponent(nuxtApp._route.fullPath)}`
                  )
                  return { data: null, error: _data }
                }
                // 必须同时更新两个 Token
                userStore.setToken({
                  accessToken: _data.result.accessToken,
                  refreshToken: _data.result.refreshToken
                })
                // ElMessage.success('token 刷新成功，请重新发送请求')
                // 用新 Token 重试请求
                const newHeaders = {
                  ...headers,
                  Authorization: `Bearer ${_data.result.accessToken}`
                }

                processQueue(null)
                return $fetch(path, {
                  ...options,
                  headers: newHeaders
                })
              } finally {
                isRefreshing = false
              }
            }

            return new Promise((resolve, reject) => {
              refreshSubscribers.push((error, newToken) => {
                if (error) return reject(error)
                
                resolve($fetch(path, {
                  ...options,
                  headers: {
                    ...headers,
                    Authorization: `Bearer ${newToken}`
                  }
                }))
              })
            })
          }
        }
      })
      return { data: response, error: null }
    } catch (error) {
      console.error('Fetch error:', error)
      // ElMessage.error('请求失败,code:' + error?.status)
      return { data: null, error }
    }
  }

  nuxtApp.provide('fetchGov', createFetchHandler(false))
  nuxtApp.provide('fetchAuth', createFetchHandler(true))
})